"use strict"

var Router = require('koa-router');
var config = require('../../../config/config.js');
var Category = require('../../../model/category.js');
var CategoryDao = require('../../../modelDao/category.js');

console.log('---load router---' + config.baseUrl + '/v1/category');

var router = new Router({
    prefix: config.baseUrl + '/v1/category'
});

router.get('/test', function*() {
    // console.log('%s %s', this.method, this.url);
    this.body = 'test work fine';
});


/**
{
    "name": "护理",
    "desc":"护理"
    "pCode":""  //  父id,没有可以不写
}
*/

router.post('/', function*() {
    console.log(this.request.body);
    // this.body =  this.request.body; //echo
    var inParams = this.request.body;
    inParams = JSON.parse(inParams); // 居然要转换一次
    var category = new Category({
        pCode: inParams.pCode || null,
        name: inParams.name,
        desc: inParams.desc || ''
    });

    console.log(category);

    // 
    try {
        var result = yield CategoryDao.save(category);
        // console.log(result); //save的结果，包含了_id
        this.body = JSON.stringify(result);
    } catch (e) {
        this.body = 'save category error ' + e.toString();
    }
});

// save lots of category
// {
//  "name": "护理",
//  "desc":"护理",
//  "subCategory":[{},{}]
// }

router.post('/batch', function*() {
    var docs = this.request.body;
    docs = JSON.parse(docs);
    // console.log(docs);
    var list = [];
    list.unshift(docs);

    var count = 0;
    while (list.length !== 0) {
        var curr = list.pop();
        var category = new Category({
            pCode: curr.pCode || null,
            name: curr.name,
            desc: curr.desc || ''
        });

        // var result = yield category.save();
        var result = yield CategoryDao.save(category);
        // console.log(result);
        count++;
        var pCode = result._id;

        var subs = curr.subCategory || []; // also list
        subs.forEach(function(item) {
            item.pCode = pCode;
            list.unshift(item);
        });
    }

    this.body = 'save count:' + count;

})

router.get('/list', function*() {
    // var category = yield Category.find({}).exec();
    var category = yield CategoryDao.findAll();
    // console.log(category);
    this.body = category;
});

router.get('/:id', function*() {
    // var category = yield Category.findOne({
    //  _id: this.params.id
    // }).exec();
    console.log(this.params.id);
    var category = yield CategoryDao.findById(this.params.id);
    this.body = category;
})

module.exports = router;